import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.ftplet.Authority;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.usermanager.impl.BaseUser;
import org.apache.ftpserver.usermanager.impl.WritePermission;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;

public class Ftpd {
    public static void ftp(int port,String homeDirectory) {
        FtpServerFactory serverFactory = new FtpServerFactory();
        ListenerFactory factory = new ListenerFactory();
        factory.setPort(port);
        serverFactory.addListener("default", factory.createListener());

        BaseUser user = new BaseUser();
        user.setName("anonymous");
        user.setHomeDirectory(homeDirectory);
        user.setAuthorities(Arrays.asList((Authority) new WritePermission()));
        FtpServer server = serverFactory.createServer();
        try {
            serverFactory.getUserManager().save(user);
            server.start();
        } catch (FtpException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws UnknownHostException {
        Logger logger= LoggerFactory.getLogger(Ftpd.class);
        String ip=InetAddress.getLocalHost().getHostAddress();
        File[] roots=File.listRoots();

        for (int i = 0; i < roots.length; i++) {
            int port = 2121*(i+1);
            String homeDirectory=roots[i].getAbsolutePath();
            ftp(port,homeDirectory);
            logger.info("{} ftp://{}:{}",homeDirectory,ip,port);
        }


    }
}
